<?php

namespace App\Services;

use App\Exceptions\AdminInvalidRequestException;
use App\Models\Material;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Storage;

class MaterialService
{

    /**
     * 上传资料文件
     * @param int $project_id
     * @param array $material
     * @throws AdminInvalidRequestException
     */
    public function upload(int $project_id, array $material)
    {
        try {
            $data = [];
            $storage = Storage::disk('public');
            foreach ($material as $item) {
                //1.组装资料数据
                $item_data['project_id'] = $project_id;
                $item_data['name'] = Arr::last(explode('/', $item));
                $ext = Arr::last(explode('.', $item));
                $item_data['path'] = 'files/' . now()->year . '/' . now()->month . '/' . now()->day . '/' . md5(uniqid()) . '.' . $ext;
                $item_data['size'] = $storage->size($item);
                $item_data['ext'] = $ext;
                $item_data['created_at'] = now();
                $item_data['updated_at'] = now();
                $data[] = $item_data;
                //2.修改文件名称，并移动文件位置
                $storage->move($item, $item_data['path']);
            }
            Material::query()->insert($data);
        } catch (\Exception $exception) {
            throw new AdminInvalidRequestException('上传失败，错误信息：' . $exception->getMessage());
        }
    }
}
